package com.bgds.sys.data.iXCom29d.protocol;

import com.alibaba.fastjson.JSON;
import com.bgds.sys.data.iXCom29d.protocol.utils.IXComActionParamDTO;
import com.bgds.sys.data.iXCom29d.protocol.utils.IXComCodecService;
import com.cisdi.data.common.exception.BusinessException;

import com.cisdi.data.sdk.consts.ServiceName;
import com.cisdi.data.sdk.gateway.message.SocketMessage;
import com.cisdi.data.sdk.procotol.SocketProtocol;
import com.cisdi.data.sdk.procotol.base.ProtocolBase;
import com.cisdi.data.sdk.procotol.message.SocketReturnMessage;
import com.cisdi.data.sdk.service.DynamicCodecService;
import com.cisdi.data.sdk.vo.DecodeVo;
import com.cisdi.data.sdk.vo.ReturnVo;

import java.nio.charset.Charset;
import java.util.Map;

/**
 * @author: lhp
 * @date: 2019/10/8
 **/
public class IXCom29DStringSocketProtocol extends ProtocolBase implements SocketProtocol {
	
    @Override
    public DecodeVo deCode(SocketMessage message) {
        if (message == null || message.getRunId() == null || message.getPropsMap() == null || message.getDeviceId() == null) {
            throw new BusinessException("解析入参错误1,msg为:" + message.toString());
        }        
        
        DynamicCodecService service = (DynamicCodecService)serviceProvider.getByName(ServiceName.DynamicCodec);
        if (service == null || !(service instanceof DynamicCodecService)) {
            throw new BusinessException("获取DynamicCodecService失败");
        }
        
        String paramObj = service.findByRunIdAndMsgKey(message.getRunId(), message.getMsgKey());
        Charset charset = Charset.forName(String.valueOf(message.getPropsMap().get("charset")));
        
        byte[] data = message.getData();
        
        if(data == null || paramObj == null) {
        	throw new BusinessException("解析入参错误2,msg为:" + message.toString());
        }
        
        IXComActionParamDTO dto = JSON.parseObject(paramObj, IXComActionParamDTO.class);
        
        if(dto == null || dto.getPropertyList().size() == 0) {
        	throw new BusinessException("解析入参错误3,msg为:" + message.toString());
        }
        
        DecodeVo vo = new DecodeVo();
        
        IXComCodecService defaultService = new IXComCodecService();
        Map<String,Object> map = defaultService.decode(dto, data, charset);
        vo.setData(map);
        return vo;
    }

    @Override
    public SocketReturnMessage enCode(ReturnVo returnVo) {
    	throw new BusinessException("宝信iXCom和IXCom29d连接驱动不支持下发命令功能");
    }
}